package com.zlx.controller;

import com.alibaba.fastjson.JSONObject;
import com.zlx.constants.Constant;
import com.zlx.entities.User;
import com.zlx.service.UserService;
import com.zlx.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

/**
 * @ClassName QqLoginServlet
 * @Description TODO
 * @Author Edward
 * @Date 2020/10/1 21:29
 */
@WebServlet("/qq_login")
public class QqLoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            HttpSession session = request.getSession();
            String code = request.getParameter("code");
            Properties properties = new Properties();
            properties.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
            String appid = properties.getProperty("qq.AppID");
            String AppSecret = properties.getProperty("qq.AppKey");
            String baseUrl = properties.getProperty("qq.redirect_uri");
            //如果成功返回，即可在返回包中获取到Access Token
            String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" +//必选，此值固定为“authorization_code”
                    "&client_id=" + appid +
                    "&client_secret=" + AppSecret +
                    "&code=" + code +   //上一步返回的authorization code，url带着的参数
                    "&redirect_uri=" + baseUrl; //与上面一步中传入的redirect_uri保持一致。
            //模拟http请求，获取token
            String access_token = getAccessToken(url);
            //根据token获取openId
            url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
            String openID = getOpenID(url);
            //调用qq用户信息的json串api地址
            url = "https://graph.qq.com/user/get_user_info?access_token=" +access_token+
                    "&oauth_consumer_key=" +appid+
                    "&openid=" + openID;
            User user = userService.findByQqOpenId(openID);
            if (user == null) {
                //发送模拟的http请求，获取并返回qq用户信息的json串
                JSONObject userInfo = HttpUtils.getUserInfo(url);
                System.out.println(userInfo);
                user = new User();
                user.setPic(userInfo.getString("figureurl_2"));
                user.setGender(userInfo.getString("gender_type"));
                user.setRealName(userInfo.getString("nickname"));
                user.setUsername(UUID.randomUUID().toString().substring(36 - 15));
                user.setQqOpenid(openID);
                System.out.println(user);
                userService.insertUser(user);
                user=userService.findByQqOpenId(openID);
            }
            session.setAttribute(Constant.LOGIN_USER,user);
            response.sendRedirect("/user/list");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getAccessToken(String url) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String token = null;

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            if (result.indexOf("access_token") >= 0) {
                String[] array = result.split("&");
                for (String str : array) {
                    if (str.indexOf("access_token") >= 0) {
                        token = str.substring(str.indexOf("=") + 1);
                        break;
                    }
                }
            }
        }
        httpGet.releaseConnection();
        return token;
    }


    public static String getOpenID(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = parseJSONP(result);
        }
        httpGet.releaseConnection();
        if (jsonObject != null) {
            return jsonObject.getString("openid");
        } else {
            return null;
        }
    }
    private static JSONObject parseJSONP(String jsonp) {
        int startIndex = jsonp.indexOf("(");
        int endIndex = jsonp.lastIndexOf(")");
        String json = jsonp.substring(startIndex + 1, endIndex);
        return JSONObject.parseObject(json);
    }
}
